//
//  PersonPurchasesHistoryViewController.m
//  消费100
//
//  Created by eliot on 16/4/5.
//  Copyright © 2016年 aleven. All rights reserved.
//

#import "PersonPurchasesHistoryViewController.h"
#import "PurchasesTableViewCell.h"
#import "SecurityUtil.h"
#import "GTMBase64.h"
#import "MJrefresh.h"
#import "UIImageView+WebCache.h"
#import "ResultForPurchaseOfMySelfTableViewCell.h"
@interface PersonPurchasesHistoryViewController ()<UITableViewDataSource, UITableViewDelegate>


@property (weak, nonatomic) IBOutlet UIView *btnBGV;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *btnBGVW;


@property (weak, nonatomic) IBOutlet UIButton *allBtn;

@property (weak, nonatomic) IBOutlet UIButton *resultBtn;


@property (weak, nonatomic) IBOutlet UITableView *tableView;


@property (nonatomic, strong) NSMutableArray *firsrArr;

@property (nonatomic, strong) NSMutableArray *secondArr;

@property (nonatomic, assign) BOOL allBtnSelected;

@end

@implementation PersonPurchasesHistoryViewController

static int page = 1;

- (void)dealloc {
    page = 1;
}


+(PersonPurchasesHistoryViewController*)CreatPersonPurchasesHistoryViewController{
    
    UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    PersonPurchasesHistoryViewController *PersonPurchasesHistoryViewController=[story instantiateViewControllerWithIdentifier:@"PersonPurchasesHistoryViewController"];
    return PersonPurchasesHistoryViewController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"众购记录";
    /** 注册*/
    [self.tableView registerNib:[UINib nibWithNibName:@"PurchasesTableViewCell" bundle:nil] forCellReuseIdentifier:@"PurchasesTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ResultForPurchaseOfMySelfTableViewCell" bundle:nil] forCellReuseIdentifier:@"ResultForPurchaseOfMySelfTableViewCell"];
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.backgroundColor = [UIColor colorWithRed:232/255.0 green:233/255.0 blue:232/255.0 alpha:1];
    self.allBtn.backgroundColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    self.navigationController.navigationBar.translucent = NO;
    
    
    self.allBtnSelected = YES;
    
    self.btnBGV.layer.borderWidth = 1;
    self.btnBGV.layer.borderColor = [[UIColor colorWithRed:232/255.0 green:233/255.0 blue:232/255.0 alpha:1] CGColor];
    self.btnBGV.layer.cornerRadius = 4;
    self.btnBGV.layer.masksToBounds = YES;
    self.btnBGVW.constant = 160 / 320.0 *Width;
    [self.resultBtn setTitleColor:[UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1] forState:UIControlStateNormal];
    
    
    UserModel *model = userModel;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"page":@"1",@"consumerId":model.id,@"type":@"1"};
    NSString *baseUrl = [NSString stringWithFormat:@"%@getCrowdfundingsOrderByConsumerId.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.firsrArr = [NSMutableArray arrayWithArray:[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]];
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];
    
    MJRefreshBackGifFooter *footer = [MJRefreshBackGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer = footer;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    
    
    
    
    
}


- (void)loadMoreData {
    page += 1;
    if (self.allBtn.selected) {
        
        UserModel *model = userModel;
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer.timeoutInterval = 5;
        NSDictionary *dic = @{@"page":[NSString stringWithFormat:@"%d", page],@"consumerId":[SecurityUtil encryptAESData:model.id],@"type":@"1"};
        NSString *baseUrl = [NSString stringWithFormat:@"%@getCrowdfundingsOrderByConsumerId.jhtml", MyBaseURL];
        [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.firsrArr addObjectsFromArray:[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]];
                [self.tableView reloadData];
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"链接超时,请检查网络"];
            });
        }];
        
    }else {
        
        UserModel *model = userModel;
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer.timeoutInterval = 5;
        NSDictionary *dic = @{@"page":[NSString stringWithFormat:@"%d", page],@"consumerId":[SecurityUtil encryptAESData:model.id],@"type":@"0"};
        NSString *baseUrl = [NSString stringWithFormat:@"%@getCrowdfundingsOrderByConsumerId.jhtml", MyBaseURL];
        [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.secondArr addObjectsFromArray:[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]];
                [self.tableView reloadData];
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"链接超时,请检查网络"];
            });
        }];
    
    
    }

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


/** 点击全部按钮*/

- (IBAction)clickAnnBtn:(id)sender {
    self.allBtn.backgroundColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    self.resultBtn.backgroundColor = [UIColor whiteColor];
    [self.resultBtn setTitleColor:[UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1] forState:UIControlStateNormal];
    [self.allBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    self.allBtnSelected = YES;
     page = 1;
    
    
    UserModel *model = userModel;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"page":[NSString stringWithFormat:@"%d", page],@"consumerId":[SecurityUtil encryptAESData:model.id],@"type":@"1"};
    NSString *baseUrl = [NSString stringWithFormat:@"%@getCrowdfundingsOrderByConsumerId.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
             [self.tableView.mj_footer endRefreshing];
            self.firsrArr = [NSMutableArray arrayWithArray:[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]];
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             [self.tableView.mj_footer endRefreshing];
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];
    
    
    
}

/** 点击已揭晓按钮*/
- (IBAction)clickResultBtn:(id)sender {
    
    page = 1;
    
    self.resultBtn.backgroundColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    self.allBtn.backgroundColor = [UIColor whiteColor];
    [self.allBtn setTitleColor:[UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1] forState:UIControlStateNormal];
    [self.resultBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    self.allBtnSelected = NO;
    
    UserModel *model = userModel;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"page":[NSString stringWithFormat:@"%d", page],@"consumerId":[SecurityUtil encryptAESData:model.id],@"type":@"0"};
    NSString *baseUrl = [NSString stringWithFormat:@"%@getCrowdfundingsOrderByConsumerId.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
      
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView.mj_footer endRefreshing];
            self.secondArr = [NSMutableArray arrayWithArray:[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]];
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
             [self.tableView.mj_footer endRefreshing];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];
    
    
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.allBtnSelected) {
        return self.firsrArr.count;
    }else {
        return self.secondArr.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.allBtnSelected) {
        PurchasesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PurchasesTableViewCell" forIndexPath:indexPath];
        cell.progressViewH.constant = 4;
        
        return cell;
    }else {
        ResultForPurchaseOfMySelfTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ResultForPurchaseOfMySelfTableViewCell" forIndexPath:indexPath];
        NSDictionary *dic = self.secondArr[indexPath.section];
        [cell.iconIV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.115:8088%@", dic[@"crowdfundingImg"]]]];
        cell.titleLb.text = dic[@"crowdfundingName"];
        cell.priceLb.text = [NSString stringWithFormat:@"￥%@", dic[@"crowdfundingPrice"]];
        cell.phoneLb.text = dic[@"consumerPhone"];
        return cell;
    
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (self.allBtnSelected) {
        return 160;
    }else {
        return 130;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
